/**
 * UI管理器 - 处理用户界面交互和状态管理
 */
export class UIManager {
    constructor(elements, callbacks = {}) {
        this.elements = elements;
        this.callbacks = callbacks;
        this.isCollapsed = false;
        this.settings = {
            voice: 'zhichu',
            autoPlay: true,
            showSubtitles: true,
            volume: 0.8
        };
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadSettings();
        this.updateUI();
    }
    
    bindEvents() {
        // 发送按钮
        if (this.elements.sendBtn) {
            this.elements.sendBtn.addEventListener('click', () => {
                this.handleSendMessage();
            });
        }
        
        // 输入框回车
        if (this.elements.textInput) {
            this.elements.textInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.handleSendMessage();
                }
            });
        }
        
        // 语音按钮
        if (this.elements.voiceBtn) {
            this.elements.voiceBtn.addEventListener('click', () => {
                this.handleVoiceToggle();
            });
        }
        
        // 面板折叠按钮
        if (this.elements.toggleBtn) {
            this.elements.toggleBtn.addEventListener('click', () => {
                this.togglePanel();
            });
        }
        
        // 设置变更
        if (this.elements.voiceSelect) {
            this.elements.voiceSelect.addEventListener('change', (e) => {
                this.settings.voice = e.target.value;
                this.saveSettings();
                this.onSettingsChange();
            });
        }
        
        if (this.elements.autoPlayCheckbox) {
            this.elements.autoPlayCheckbox.addEventListener('change', (e) => {
                this.settings.autoPlay = e.target.checked;
                this.saveSettings();
                this.onSettingsChange();
            });
        }
        
        if (this.elements.subtitlesCheckbox) {
            this.elements.subtitlesCheckbox.addEventListener('change', (e) => {
                this.settings.showSubtitles = e.target.checked;
                this.saveSettings();
                this.onSettingsChange();
                
                // 如果取消勾选，立即隐藏字幕
                if (!e.target.checked && this.elements.subtitles) {
                    console.log('用户取消勾选字幕，立即隐藏当前显示的字幕');
                    this.elements.subtitles.classList.remove('show', 'realtime');
                    this.elements.subtitles.style.opacity = '0';
                    this.elements.subtitles.style.visibility = 'hidden';
                    
                    // 清除所有字幕相关的定时器
                    this.cleanupSubtitles();
                }
                // 如果勾选，重新显示字幕
                else if (e.target.checked && this.elements.subtitles) {
                    console.log('用户勾选字幕，立即显示字幕');
                    
                    // 确保字幕文本元素存在
                    let subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
                    if (!subtitleText) {
                        const newSubtitleText = document.createElement('div');
                        newSubtitleText.id = 'subtitle-text';
                        this.elements.subtitles.appendChild(newSubtitleText);
                        subtitleText = newSubtitleText;
                    }
                    
                    // 强制显示字幕容器（先设置样式，后恢复内容，确保可见性）
                    this.elements.subtitles.classList.add('show');
                    this.elements.subtitles.style.opacity = '1';
                    this.elements.subtitles.style.visibility = 'visible';
                    
                    // 恢复适当的类（根据当前模式）
                    if (this.currentAudioContext && this.currentAudioContext.isRealtime) {
                        this.elements.subtitles.classList.add('realtime');
                    }
                    
                    // 尝试恢复当前句子内容
                    if (this.currentAudioContext) {
                        // 检查是否有句子数组和当前索引
                        if (this.currentAudioContext.sentences && this.currentAudioContext.sentences.length > 0) {
                            const currentIndex = this.currentAudioContext.currentIndex || 0;
                            if (currentIndex < this.currentAudioContext.sentences.length) {
                                const currentSentence = this.currentAudioContext.sentences[currentIndex];
                                if (currentSentence && subtitleText) {
                                    subtitleText.textContent = currentSentence.trim();
                                    console.log('已恢复当前正在播放的句子:', currentSentence.trim());
                                }
                            }
                        } 
                        // 如果有完整文本但没有句子信息，显示完整文本
                        else if (this.currentAudioContext.text && this.currentAudioContext.text.trim()) {
                            subtitleText.textContent = this.currentAudioContext.text.trim();
                            console.log('显示完整文本内容');
                        }
                    }
                    
                    // 添加动画效果
                    this.addSubtitleAnimation();
                    
                    console.log('字幕显示样式已设置:', {
                        hasShowClass: this.elements.subtitles.classList.contains('show'),
                        hasRealtimeClass: this.elements.subtitles.classList.contains('realtime'),
                        opacity: this.elements.subtitles.style.opacity,
                        visibility: this.elements.subtitles.style.visibility,
                        hasContent: subtitleText && subtitleText.textContent && subtitleText.textContent.trim()
                    });
                }
            });
        }
        
        // 错误模态框关闭
        const errorClose = document.getElementById('error-close');
        if (errorClose) {
            errorClose.addEventListener('click', () => {
                this.hideError();
            });
        }
        
        // 点击模态框背景关闭
        if (this.elements.errorModal) {
            this.elements.errorModal.addEventListener('click', (e) => {
                if (e.target === this.elements.errorModal) {
                    this.hideError();
                }
            });
        }
    }
    
    handleSendMessage() {
        const text = this.elements.textInput?.value?.trim();
        if (!text) return;
        
        if (this.callbacks.onSendMessage) {
            this.callbacks.onSendMessage(text);
        }
        
        this.elements.textInput.value = '';
        this.updateSendButton();
    }
    
    handleVoiceToggle() {
        if (this.callbacks.onVoiceToggle) {
            this.callbacks.onVoiceToggle();
        }
    }
    
    togglePanel() {
        this.isCollapsed = !this.isCollapsed;
        
        if (this.elements.controlPanel) {
            this.elements.controlPanel.classList.toggle('collapsed', this.isCollapsed);
        }
        
        if (this.elements.toggleBtn) {
            this.elements.toggleBtn.textContent = this.isCollapsed ? '▶' : '◀';
        }
        
        // 保存状态
        localStorage.setItem('panelCollapsed', this.isCollapsed.toString());
    }
    
    addMessage(type, content, timestamp = null) {
        if (!this.elements.chatHistory) return;
        
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = content;
        messageDiv.appendChild(contentDiv);
        
        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = timestamp || new Date().toLocaleTimeString();
        messageDiv.appendChild(timeDiv);
        
        this.elements.chatHistory.appendChild(messageDiv);
        this.scrollToBottom();
        
        // 添加动画效果
        messageDiv.style.opacity = '0';
        messageDiv.style.transform = 'translateY(20px)';
        
        requestAnimationFrame(() => {
            messageDiv.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            messageDiv.style.opacity = '1';
            messageDiv.style.transform = 'translateY(0)';
        });
    }
    
    scrollToBottom() {
        if (this.elements.chatHistory) {
            this.elements.chatHistory.scrollTop = this.elements.chatHistory.scrollHeight;
        }
    }
    
    updateConnectionStatus(connected) {
        const statusElement = this.elements.connectionStatus || 
                            document.querySelector('.status-value');
        
        if (statusElement) {
            statusElement.textContent = connected ? '已连接' : '未连接';
            statusElement.className = `status-value ${connected ? 'connected' : 'disconnected'}`;
        }
        
        // 更新状态指示器
        if (this.elements.statusIndicator) {
            this.elements.statusIndicator.className = `status-indicator ${connected ? 'connected' : 'disconnected'}`;
        }
    }
    
    updateVoiceStatus(status, isListening = false) {
        if (this.elements.voiceStatus) {
            this.elements.voiceStatus.textContent = status;
        }
        
        if (this.elements.voiceBtn) {
            this.elements.voiceBtn.classList.toggle('recording', isListening);
        }
    }
    
    updateThinkingStatus(thinking) {
        const statusValue = document.querySelector('.status-value.thinking') || 
                          document.querySelector('.status-value');
        
        if (statusValue) {
            if (thinking) {
                statusValue.textContent = '思考中...';
                statusValue.className = 'status-value thinking';
                
                // 添加思考动画
                this.addThinkingAnimation(statusValue);
            } else {
                statusValue.textContent = '已连接';
                statusValue.className = 'status-value connected';
                
                // 移除思考动画
                this.removeThinkingAnimation(statusValue);
            }
        }
    }
    
    addThinkingAnimation(element) {
        element.classList.add('thinking-animation');
    }
    
    removeThinkingAnimation(element) {
        element.classList.remove('thinking-animation');
    }
    
    /**
     * 显示字幕（支持实时逐字显示）
     * @param {string} text - 字幕文本
     * @param {number} duration - 显示时长（毫秒）
     * @param {boolean} realtime - 是否实时显示
     * @param {number} audioDuration - 音频总时长（秒）
     * @param {AudioManager} audioManager - 音频管理器实例（可选）
     */
    showSubtitles(text, duration = 3000, realtime = false, audioDuration = null, audioManager = null) {
        console.log('UIManager.showSubtitles called with text:', text);
        if (!this.elements.subtitles || !this.settings.showSubtitles) {
            console.log('Subtitles not shown: elements.subtitles missing or showSubtitles setting false');
            console.log('elements.subtitles exists:', !!this.elements.subtitles);
            console.log('settings.showSubtitles:', this.settings.showSubtitles);
            return;
        }
        
        // 获取内部的text元素
        const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        if (!subtitleText) {
            console.log('subtitle-text element not found');
            return;
        }

        console.log('subtitleText element found:', subtitleText);

        // 清除之前的定时器
        if (this.subtitleTimer) {
            clearTimeout(this.subtitleTimer);
        }
        if (this.realtimeTimer) {
            clearInterval(this.realtimeTimer);
        }
        
        // 移除之前可能存在的音频进度监听器
        if (this.progressListener) {
            try {
                audioManager?.off('progress', this.progressListener);
            } catch (e) {
                console.warn('Failed to remove previous progress listener:', e);
            }
            this.progressListener = null;
        }

        if (realtime && audioDuration) {
            if (audioManager) {
                // 使用音频管理器的进度事件来同步显示字幕
                this.showAudioSyncedSubtitles(text, audioDuration, audioManager);
            } else {
                // 实时字幕模式 - 逐字显示
                this.showRealtimeCharByCharSubtitles(text, audioDuration);
            }
        } else {
            console.log('Setting subtitle text:', text);
            // 传统模式：一次性显示完整文本
            subtitleText.textContent = text;
            this.elements.subtitles.classList.add('show');
            console.log('Subtitles class list after adding show:', this.elements.subtitles.classList);

            // 设置隐藏定时器
            this.subtitleTimer = setTimeout(() => {
                this.elements.subtitles.classList.remove('show');
            }, duration);
        }
    }

    /**
     * 清理字幕相关资源
     */
    cleanupSubtitles() {
        // 清除定时器
        if (this.subtitleTimer) {
            clearTimeout(this.subtitleTimer);
            this.subtitleTimer = null;
        }
        if (this.realtimeTimer) {
            clearInterval(this.realtimeTimer);
            this.realtimeTimer = null;
        }
        
        // 移除音频进度监听器
        if (this.currentAudioManager && 
            typeof this.currentAudioManager.off === 'function' && 
            this.audioProgressListener) {
            this.currentAudioManager.off('timeupdate', this.audioProgressListener);
            this.audioProgressListener = null;
        }
        
        // 移除之前可能存在的音频进度监听器
        if (this.progressListener) {
            try {
                // 如果存在旧的监听器，尝试移除它
                this.progressListener = null;
            } catch (e) {
                console.warn('Failed to remove previous progress listener:', e);
            }
        }
        
        // 隐藏字幕
        if (this.elements.subtitles) {
            this.elements.subtitles.classList.remove('show', 'realtime');
        }
        
        // 清除当前音频上下文
        this.currentAudioContext = null;
        this.currentAudioManager = null;
        
        console.log('Subtitles cleaned up');
    }
    
    /**
     * 清理字幕相关资源
     */
    cleanupSubtitles() {
        if (this.subtitleTimer) {
            clearTimeout(this.subtitleTimer);
            this.subtitleTimer = null;
        }
        if (this.realtimeTimer) {
            clearInterval(this.realtimeTimer);
            this.realtimeTimer = null;
        }
        
        // 立即隐藏字幕（不使用延迟，确保用户取消勾选时字幕立即消失）
        if (this.elements.subtitles) {
            this.elements.subtitles.classList.remove('realtime');
            this.elements.subtitles.classList.remove('show');
            this.elements.subtitles.style.opacity = '0';
            this.elements.subtitles.style.visibility = 'hidden';
        }
        
        console.log('Subtitles cleaned up and hidden immediately');
    }

    /**
     * 显示实时字幕（逐句显示）
     * @param {string} text - 要显示的文本
     * @param {number} audioDuration - 音频总时长（秒）
     * @param {Array} timestamps - 时间戳数据（可选）
     * @param {AudioManager} audioManager - 音频管理器实例（可选）
     */
    showRealtimeSubtitles(text, audioDuration, timestamps = null, audioManager = null) {
        console.log('UIManager.showRealtimeSubtitles called with text:', text, 'audioDuration:', audioDuration, 'timestamps:', timestamps, 'audioManager:', audioManager);
        
        // 清除之前的字幕定时器和事件监听器
        this.cleanupSubtitles();
        
        if (!text || !audioDuration) {
            console.log('Invalid text or audioDuration for realtime subtitles');
            return;
        }

        if (!this.elements.subtitles || !this.settings.showSubtitles) {
            console.log('Realtime subtitles not shown: elements.subtitles missing or showSubtitles setting false');
            return;
        }

        // 初始化显示
        this.elements.subtitles.classList.add('show', 'realtime');
        console.log('Subtitles classes after adding show and realtime:', this.elements.subtitles.classList);
        
        // 标记当前为实时模式
        if (!this.currentAudioContext) {
            this.currentAudioContext = {};
        }
        this.currentAudioContext.isRealtime = true;
        
        // 如果提供了audioManager，使用音频进度同步字幕
        if (audioManager) {
            console.log('Using audio progress synced subtitles');
            this.showAudioSyncedSubtitles(text, audioDuration, timestamps, audioManager);
        } else {
            // 如果有时间戳数据，使用精确时间戳显示
            if (timestamps && Array.isArray(timestamps) && timestamps.length > 0) {
                console.log('Using timestamp-based subtitles with', timestamps.length, 'timestamps');
                this.showTimestampBasedSubtitles(timestamps, audioDuration);
            } else {
                // 降级到逐字显示方案
                console.log('No valid timestamps, falling back to char by char subtitles');
                this.showRealtimeCharByCharSubtitles(text, audioDuration);
            }
        }
    }
    
    /**
     * 基于音频进度的同步字幕显示
     * @param {string} text - 要显示的文本
     * @param {number} duration - 音频总时长（秒）
     * @param {Array} timestamps - 时间戳数据（可选）
     * @param {Object} audioManager - 音频管理器实例
     */
    showAudioSyncedSubtitles(text, duration, timestamps, audioManager) {
        console.log('UIManager.showAudioSyncedSubtitles called with text:', text, 'duration:', duration, 'audioManager:', audioManager);
        
        // 首先检查设置和元素是否存在
        if (!this.elements.subtitles || !this.settings.showSubtitles) {
            console.log('Subtitles not shown: elements.subtitles missing or showSubtitles setting false');
            console.log('elements.subtitles exists:', !!this.elements.subtitles);
            console.log('settings.showSubtitles:', this.settings.showSubtitles);
            return;
        }
        
        // 清除之前的字幕
        this.cleanupSubtitles();
        
        // 获取字幕元素
        const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        if (!subtitleText) {
            console.warn('subtitle-text element not found');
            return;
        }
        
        // 存储音频管理器引用，用于后续清理
        this.currentAudioManager = audioManager;
        
        // 显示字幕容器
        this.elements.subtitles.classList.add('show', 'realtime');
        
        // 处理字幕逻辑
        let sentences = [];
        
        // 优先使用时间戳数据
        if (timestamps && Array.isArray(timestamps) && timestamps.length > 0) {
            sentences = timestamps;
        } else {
            // 否则按句子分割文本
            const splitSentences = this.splitTextIntoSentences(text);
            sentences = splitSentences.map((sentence, index) => {
                return {
                    text: sentence,
                    start_time: index * (duration / splitSentences.length),
                    end_time: (index + 1) * (duration / splitSentences.length)
                };
            });
        }
        
        // 设置初始显示
        if (sentences.length > 0) {
            subtitleText.textContent = sentences[0].text.trim();
            this.addSubtitleAnimation();
        }
        
        // 保存当前音频上下文
        this.currentAudioContext = {
            text,
            duration,
            timestamps,
            sentences,
            currentSentenceIndex: 0
        };
        
        // 监听音频时间更新事件
        const onTimeUpdate = (event) => {
            const currentTime = event.currentTime || 0;
            
            // 如果有时间戳，根据时间戳更新字幕
            if (sentences.length > 0) {
                // 查找当前应该显示的句子
                for (let i = 0; i < sentences.length; i++) {
                    const sentence = sentences[i];
                    
                    // 改进的时间范围检查，确保即使在音频跳跃时也能正确显示
                    if (currentTime >= sentence.start_time && 
                        (i === sentences.length - 1 || currentTime < sentences[i + 1].start_time)) {
                        
                        // 如果句子发生变化，更新字幕
                        if (i !== this.currentAudioContext.currentSentenceIndex) {
                            this.currentAudioContext.currentSentenceIndex = i;
                            subtitleText.textContent = sentence.text.trim();
                            this.addSubtitleAnimation();
                            console.log('Updated subtitle to:', sentence.text.trim());
                        }
                        break;
                    }
                }
            }
        };
        
        // 保存事件监听器引用
        this.audioProgressListener = onTimeUpdate;
        
        // 添加事件监听器
        if (audioManager && typeof audioManager.on === 'function') {
            // 确保移除之前可能存在的监听器，防止多次绑定
            if (typeof audioManager.off === 'function') {
                audioManager.off('timeupdate', this.audioProgressListener);
            }
            // 添加新的监听器
            audioManager.on('timeupdate', onTimeUpdate);
            console.log('Added timeupdate listener to audioManager');
        }
        
        // 设置最终隐藏定时器
        this.subtitleTimer = setTimeout(() => {
            console.log('Hiding subtitles after audio duration:', duration, 's');
            this.cleanupSubtitles();
        }, (duration + 1) * 1000); // 音频结束后额外显示1秒
    }
    
    /**
     * 实时逐字显示字幕
     * @param {string} text - 要显示的文本
     * @param {number} audioDuration - 音频总时长（秒）
     */
    showRealtimeCharByCharSubtitles(text, audioDuration) {
        console.log('UIManager.showRealtimeCharByCharSubtitles called with text:', text, 'audioDuration:', audioDuration);
        
        if (!text || !audioDuration) {
            console.log('Invalid text or audioDuration for char by char subtitles');
            return;
        }
        
        // 获取内部的text元素
        const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        if (!subtitleText) {
            console.log('subtitle-text element not found in showRealtimeCharByCharSubtitles');
            return;
        }

        // 初始化显示
        this.elements.subtitles.classList.add('show', 'realtime');
        console.log('Subtitles classes after adding show and realtime:', this.elements.subtitles.classList);
        
        // 准备文本，控制显示长度
        const maxDisplayLength = 20; // 最多同时显示20个字符
        const chars = Array.from(text);
        let currentIndex = 0;
        let displayedText = '';
        
        console.log('Preparing to display', chars.length, 'characters with max display length of', maxDisplayLength);
        
        // 计算每个字符的显示间隔（毫秒）
        // 预留5%的时间缓冲
        const availableTime = audioDuration * 0.95 * 1000;
        const charInterval = chars.length > 0 ? availableTime / chars.length : 100;
        
        console.log('Calculated char interval:', charInterval, 'ms');
        
        // 立即显示第一个字符
        if (chars.length > 0) {
            displayedText = chars[0];
            subtitleText.textContent = displayedText;
            this.addSubtitleAnimation();
            currentIndex = 1;
            console.log('Displayed first character:', displayedText);
        }
        
        // 如果只有一个字符，直接显示并设置隐藏定时器
        if (chars.length <= 1) {
            console.log('Only one character to display, setting final timer');
            this.elements.subtitles.classList.remove('realtime');
            this.subtitleTimer = setTimeout(() => {
                this.elements.subtitles.classList.remove('show');
                console.log('Subtitles hidden after single character display');
            }, Math.max(audioDuration * 1000, 2000));
            return;
        }
        
        // 设置实时逐字显示定时器
        this.realtimeTimer = setInterval(() => {
            if (currentIndex < chars.length) {
                // 添加下一个字符
                displayedText += chars[currentIndex];
                
                // 如果显示的文本超过最大长度，从左侧移除旧字符
                if (displayedText.length > maxDisplayLength) {
                    displayedText = displayedText.slice(-maxDisplayLength);
                }
                
                subtitleText.textContent = displayedText;
                console.log('Displaying characters:', displayedText, 'at index', currentIndex);
                this.addSubtitleAnimation();
                currentIndex++;
            } else {
                // 显示完成，清除定时器
                clearInterval(this.realtimeTimer);
                this.realtimeTimer = null;
                this.elements.subtitles.classList.remove('realtime');
                console.log('Finished displaying all characters');
                
                // 保持显示一段时间后隐藏
                this.subtitleTimer = setTimeout(() => {
                    this.elements.subtitles.classList.remove('show');
                    console.log('Subtitles hidden after completion');
                }, 2000);
            }
        }, charInterval);
    }

    /**
     * 基于时间戳的精确字幕显示
     * @param {Array} timestamps - 时间戳数据
     * @param {number} audioDuration - 音频总时长（秒）
     */
    showTimestampBasedSubtitles(timestamps, audioDuration) {
        console.log('UIManager.showTimestampBasedSubtitles called with timestamps count:', timestamps.length, 'audioDuration:', audioDuration);
        
        if (!this.elements.subtitles || !this.settings.showSubtitles) {
            console.log('Timestamp-based subtitles not shown: elements.subtitles missing or showSubtitles setting false');
            return;
        }
        
        // 获取内部的text元素
        const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        if (!subtitleText) {
            console.log('subtitle-text element not found in showTimestampBasedSubtitles');
            return;
        }
        
        let currentIndex = 0;
        const totalSentences = timestamps.length;
        
        // 立即显示第一句字幕
        if (totalSentences > 0) {
            subtitleText.textContent = timestamps[0].text.trim();
            console.log('Displaying first timestamp text:', timestamps[0].text.trim());
            this.addSubtitleAnimation();
            currentIndex = 1;
        }
        
        // 如果只有一句话，设置隐藏定时器
        if (totalSentences <= 1) {
            this.elements.subtitles.classList.remove('realtime');
            console.log('Only one timestamp sentence, setting hide timer for:', Math.max(audioDuration * 1000, 2000), 'ms');
            this.subtitleTimer = setTimeout(() => {
                console.log('Hiding single timestamp subtitle');
                this.elements.subtitles.classList.remove('show');
            }, Math.max(audioDuration * 1000, 2000));
            return;
        }
        
        // 为每个后续句子设置精确的定时器
        for (let i = 1; i < totalSentences; i++) {
            const timestamp = timestamps[i];
            const delay = timestamp.start_time * 1000; // 转换为毫秒
            
            setTimeout(() => {
                if (this.elements.subtitles && this.elements.subtitles.classList.contains('realtime')) {
                    subtitleText.textContent = timestamp.text.trim();
                    console.log('Displaying timestamp text at', timestamp.start_time, 's:', timestamp.text.trim());
                    this.addSubtitleAnimation();
                }
            }, delay);
        }
        
        // 设置最终隐藏定时器
        const lastTimestamp = timestamps[totalSentences - 1];
        const hideDelay = (lastTimestamp.end_time + 1) * 1000; // 在最后一句结束后1秒隐藏
        
        console.log('Setting final subtitle hide timer for:', hideDelay, 'ms after end of last timestamp');
        this.subtitleTimer = setTimeout(() => {
            console.log('Hiding all subtitles after timestamp sequence completion');
            this.elements.subtitles.classList.remove('show', 'realtime');
        }, hideDelay);
    }

    /**
     * 基于句子字数动态计算显示时间的字幕显示
     * 根据每读10个字3～4秒的速度计算显示时间
     * @param {string} text - 要显示的文本
     * @param {number} audioDuration - 音频总时长（秒）
     */
    showIntervalBasedSubtitles(text, audioDuration) {
        console.log('UIManager.showIntervalBasedSubtitles called with text:', text, 'audioDuration:', audioDuration);
        
        // 首先检查设置和元素是否存在
        if (!this.elements.subtitles) {
            console.error('字幕容器元素不存在，请检查HTML结构');
            return;
        }
        
        if (!this.settings.showSubtitles) {
            console.log('字幕功能已禁用，可通过设置启用');
            return;
        }
        
        console.log('准备显示字幕:', text);
        
        // 清除之前的字幕
        this.cleanupSubtitles();
        
        // 获取字幕元素
        let subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        if (!subtitleText) {
            console.error('subtitle-text元素不存在，请检查HTML结构');
            // 如果subtitle-text元素不存在，尝试创建它
            const newSubtitleText = document.createElement('div');
            newSubtitleText.id = 'subtitle-text';
            this.elements.subtitles.appendChild(newSubtitleText);
            subtitleText = newSubtitleText;
        }
        
        // 强制显示字幕容器
        this.elements.subtitles.classList.add('show');
        console.log('字幕容器已添加show类:', this.elements.subtitles.classList.contains('show'));
        
        // 分割文本为句子
        const sentences = this.splitTextIntoSentences(text);
        if (sentences.length === 0) {
            console.warn('没有可显示的句子');
            // 如果没有句子，直接显示完整文本
            subtitleText.textContent = text;
            // 设置隐藏定时器
            this.subtitleTimer = setTimeout(() => {
                this.elements.subtitles.classList.remove('show');
            }, 3000);
            return;
        }
        
        console.log('文本分割为', sentences.length, '个句子');
        
        let currentIndex = 0;
        
        // 先保存当前上下文，确保showSentenceAndScheduleNext中可以访问到
        this.currentAudioContext = {
            text,
            audioDuration,
            sentences,
            currentIndex,
            isRealtime: false // 默认为非实时模式
        };
        
        // 初始显示第一句并设置定时器
        this.showSentenceAndScheduleNext(sentences, currentIndex, subtitleText);
        console.log('字幕显示流程已启动');
    }
    
    /**
     * 显示当前句子并安排下一句
     * @param {Array} sentences - 句子数组
     * @param {number} index - 当前句子索引
     * @param {HTMLElement} subtitleElement - 字幕元素
     */
    showSentenceAndScheduleNext(sentences, index, subtitleElement) {
        // 检查设置，如果已禁用字幕，立即停止显示并清理
        if (!this.settings.showSubtitles) {
            console.log('Subtitles disabled, stopping subtitle display');
            this.cleanupSubtitles();
            return;
        }
        
        if (index >= sentences.length) {
            // 所有句子显示完毕，清除定时器并隐藏字幕
            this.subtitleInterval = null;
            
            // 设置最终隐藏定时器
            this.subtitleTimer = setTimeout(() => {
                console.log('Hiding subtitles after all sentences displayed');
                this.cleanupSubtitles();
            }, 1000); // 额外显示1秒
            return;
        }
        
        const currentSentence = sentences[index].trim();
        
        // 计算当前句子的显示时间（每10个字3秒，不计标点符号）
        // 过滤掉标点符号，只计算汉字和字母数字
        const charCount = currentSentence.replace(/[\p{P}\s]/gu, '').length;
        // 每10个字3秒
        const duration = (charCount / 10) * 3;
        // 确保最短显示1秒，最长不超过8秒（保持合理的显示时间范围）
        const displayDuration = Math.max(1, Math.min(8, duration));
        
        console.log(`Displaying sentence: "${currentSentence}" (${charCount} characters), duration: ${displayDuration}s`);
        
        // 显示当前句子
        subtitleElement.textContent = currentSentence;
        this.addSubtitleAnimation();
        
        // 更新当前索引
        this.currentAudioContext.currentIndex = index;
        
        // 安排下一句的显示
        this.subtitleInterval = setTimeout(() => {
            this.showSentenceAndScheduleNext(sentences, index + 1, subtitleElement);
        }, displayDuration * 1000);
    }

    /**
     * 添加字幕动画效果
     */
    addSubtitleAnimation() {
        if (!this.elements.subtitles) return;
        
        // 添加轻微的动画效果
        this.elements.subtitles.style.animation = 'none';
        this.elements.subtitles.offsetHeight; // 触发重排
        this.elements.subtitles.style.animation = 'subtitlePulse 0.3s ease-in-out';
    }

    /**
     * 智能分割文本为合适的显示片段
     * @param {string} text - 输入文本
     * @returns {Array} 分割后的片段数组
     */
    splitTextIntoSegments(text) {
        // 中文标点符号和分隔符
        const punctuation = /[，。！？；：、""''（）【】《》]/;
        const segments = [];
        let currentSegment = '';
        
        for (let i = 0; i < text.length; i++) {
            const char = text[i];
            currentSegment += char;
            
            // 遇到标点符号或达到一定长度时分割
            if (punctuation.test(char) || currentSegment.length >= 3) {
                segments.push(currentSegment);
                currentSegment = '';
            }
        }
        
        // 添加剩余的字符
        if (currentSegment) {
            segments.push(currentSegment);
        }
        
        // 如果分割后片段太少，按字符分割
        if (segments.length < 5) {
            return Array.from(text);
        }
        
        return segments;
    }
    
    /**
     * 按句子分割文本
     * @param {string} text - 输入文本
     * @returns {Array} 分割后的句子数组
     */
    splitTextIntoSentences(text) {
        if (!text) return [];
        
        // 句子结束标点符号
        const sentenceEnders = /[。！？]/;
        const sentences = [];
        let currentSentence = '';
        
        for (let i = 0; i < text.length; i++) {
            const char = text[i];
            currentSentence += char;
            
            // 遇到句子结束符时分割
            if (sentenceEnders.test(char)) {
                sentences.push(currentSentence.trim());
                currentSentence = '';
            }
        }
        
        // 添加剩余的文本
        if (currentSentence.trim()) {
            sentences.push(currentSentence.trim());
        }
        
        // 如果没有句子分割符，按逗号分割
        if (sentences.length <= 1) {
            return text.split(/[，、；：]/).filter(s => s.trim());
        }
        
        return sentences.filter(s => s.length > 0);
    }
    
    /**
     * 停止实时字幕
     */
    stopRealtimeSubtitles() {
        console.log('Stopping realtime subtitles');
        // 复用cleanupSubtitles方法，确保清理逻辑一致
        this.cleanupSubtitles();
    }
    
    showError(title, message) {
        const errorTitle = document.getElementById('error-title');
        const errorMessage = document.getElementById('error-message');
        
        if (errorTitle) errorTitle.textContent = title;
        if (errorMessage) errorMessage.textContent = message;
        
        if (this.elements.errorModal) {
            this.elements.errorModal.classList.add('show');
        }
    }
    
    hideError() {
        if (this.elements.errorModal) {
            this.elements.errorModal.classList.remove('show');
        }
    }
    
    updateSendButton() {
        if (!this.elements.sendBtn || !this.elements.textInput) return;
        
        const hasText = this.elements.textInput.value.trim().length > 0;
        this.elements.sendBtn.disabled = !hasText;
        this.elements.sendBtn.classList.toggle('active', hasText);
    }
    
    loadSettings() {
        try {
            const saved = localStorage.getItem('aiChatSettings');
            if (saved) {
                this.settings = { ...this.settings, ...JSON.parse(saved) };
            }
            
            // 加载面板状态
            const panelCollapsed = localStorage.getItem('panelCollapsed');
            if (panelCollapsed === 'true') {
                this.isCollapsed = true;
            }
        } catch (error) {
            console.warn('加载设置失败:', error);
        }
    }
    
    saveSettings() {
        try {
            localStorage.setItem('aiChatSettings', JSON.stringify(this.settings));
        } catch (error) {
            console.warn('保存设置失败:', error);
        }
    }
    
    updateUI() {
        // 更新设置UI
        if (this.elements.voiceSelect) {
            this.elements.voiceSelect.value = this.settings.voice;
        }
        
        if (this.elements.autoPlayCheckbox) {
            this.elements.autoPlayCheckbox.checked = this.settings.autoPlay;
        }
        
        if (this.elements.subtitlesCheckbox) {
            this.elements.subtitlesCheckbox.checked = this.settings.showSubtitles;
        }
        
        // 更新面板状态
        if (this.isCollapsed && this.elements.controlPanel) {
            this.elements.controlPanel.classList.add('collapsed');
            if (this.elements.toggleBtn) {
                this.elements.toggleBtn.textContent = '▶';
            }
        }
        
        // 监听输入框变化
        if (this.elements.textInput) {
            this.elements.textInput.addEventListener('input', () => {
                this.updateSendButton();
            });
            this.updateSendButton();
        }
    }
    
    onSettingsChange() {
        if (this.callbacks.onSettingsChange) {
            this.callbacks.onSettingsChange(this.settings);
        }
    }
    
    // 获取当前设置
    getSettings() {
        return { ...this.settings };
    }
    
    // 更新设置
    updateSettings(newSettings) {
        this.settings = { ...this.settings, ...newSettings };
        this.saveSettings();
        this.updateUI();
        this.onSettingsChange();
    }
    
    // 显示加载状态
    showLoading(message = '加载中...') {
        if (this.elements.loadingScreen) {
            const loadingText = this.elements.loadingScreen.querySelector('.loading-text');
            if (loadingText) {
                loadingText.textContent = message;
            }
            this.elements.loadingScreen.style.display = 'flex';
            this.elements.loadingScreen.style.opacity = '1';
        }
    }
    
    // 隐藏加载状态
    hideLoading() {
        if (this.elements.loadingScreen) {
            this.elements.loadingScreen.style.opacity = '0';
            setTimeout(() => {
                this.elements.loadingScreen.style.display = 'none';
            }, 500);
        }
    }
    
    /**
     * 与音频进度同步的字幕显示
     * @param {string} text - 要显示的文本
     * @param {number} duration - 音频总时长（秒）
     * @param {Array} timestamps - 时间戳数据（可选）
     * @param {Object} audioManager - 音频管理器实例
     */
    showAudioSyncedSubtitles(text, duration, timestamps, audioManager) {
        console.log('UIManager.showAudioSyncedSubtitles called with text:', text, 'duration:', duration, 'audioManager:', audioManager);
        
        // 首先检查设置和元素是否存在
        if (!this.elements.subtitles || !this.settings.showSubtitles) {
            console.log('Subtitles not shown: elements.subtitles missing or showSubtitles setting false');
            console.log('elements.subtitles exists:', !!this.elements.subtitles);
            console.log('settings.showSubtitles:', this.settings.showSubtitles);
            return;
        }
        
        // 清除之前的字幕
        this.cleanupSubtitles();
        
        // 获取字幕元素
        const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        if (!subtitleText) {
            console.warn('subtitle-text element not found');
            return;
        }
        
        // 存储音频管理器引用，用于后续清理
        this.currentAudioManager = audioManager;
        
        // 显示字幕容器
        this.elements.subtitles.classList.add('show', 'realtime');
        
        // 处理字幕逻辑
        let sentences = [];
        let currentSentenceIndex = 0;
        
        // 优先使用时间戳数据
        if (timestamps && Array.isArray(timestamps) && timestamps.length > 0) {
            sentences = timestamps;
        } else {
            // 否则按句子分割文本
            sentences = this.splitTextIntoSentences(text).map((sentence, index) => {
                return {
                    text: sentence,
                    start_time: index * (duration / sentences.length),
                    end_time: (index + 1) * (duration / sentences.length)
                };
            });
        }
        
        // 设置初始显示
        if (sentences.length > 0) {
            subtitleText.textContent = sentences[0].text.trim();
            this.addSubtitleAnimation();
        }
        
        // 保存当前音频上下文
        this.currentAudioContext = {
            text,
            duration,
            timestamps,
            sentences,
            currentSentenceIndex: 0
        };
        
        // 监听音频时间更新事件
        const onTimeUpdate = (event) => {
            const currentTime = event.currentTime || 0;
            
            // 如果有时间戳，根据时间戳更新字幕
            if (sentences.length > 0) {
                // 查找当前应该显示的句子
                for (let i = 0; i < sentences.length; i++) {
                    const sentence = sentences[i];
                    
                    // 检查当前时间是否在句子的显示范围内
                    if (currentTime >= sentence.start_time && 
                        (i === sentences.length - 1 || currentTime < sentences[i + 1].start_time)) {
                        
                        // 如果句子发生变化，更新字幕
                        if (i !== this.currentAudioContext.currentSentenceIndex) {
                            this.currentAudioContext.currentSentenceIndex = i;
                            subtitleText.textContent = sentence.text.trim();
                            this.addSubtitleAnimation();
                            console.log('Updated subtitle to:', sentence.text.trim());
                        }
                        break;
                    }
                }
            }
        };
        
        // 保存事件监听器引用
        this.audioProgressListener = onTimeUpdate;
        
        // 添加事件监听器
        if (audioManager && typeof audioManager.on === 'function') {
            audioManager.on('timeupdate', onTimeUpdate);
        }
        
        // 设置最终隐藏定时器
        this.subtitleTimer = setTimeout(() => {
            console.log('Hiding subtitles after audio duration:', duration, 's');
            this.cleanupSubtitles();
        }, (duration + 1) * 1000); // 音频结束后额外显示1秒
    }
    
    /**
     * 清理字幕资源
     */
    cleanupSubtitles() {
        // 清除定时器
        if (this.subtitleTimer) {
            clearTimeout(this.subtitleTimer);
            this.subtitleTimer = null;
        }
        if (this.realtimeTimer) {
            clearInterval(this.realtimeTimer);
            this.realtimeTimer = null;
        }
        // 清除基于间隔的字幕定时器
        if (this.subtitleInterval) {
            clearTimeout(this.subtitleInterval);
            this.subtitleInterval = null;
        }
        
        // 移除音频进度监听器
        if (this.currentAudioManager && 
            typeof this.currentAudioManager.off === 'function' && 
            this.audioProgressListener) {
            this.currentAudioManager.off('timeupdate', this.audioProgressListener);
            this.audioProgressListener = null;
        }
        
        // 隐藏字幕
        if (this.elements.subtitles) {
            this.elements.subtitles.classList.remove('show', 'realtime');
        }
        
        // 清除当前音频上下文
        this.currentAudioContext = null;
        this.currentAudioManager = null;
    }

    /**
     * 添加通知
     */
    showNotification(message, type = 'info', duration = 3000) {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 显示动画
        requestAnimationFrame(() => {
            notification.classList.add('show');
        });
        
        // 自动隐藏
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, duration);
    }

    /**
     * 更新音频播放进度
     * @param {Object} progress - 播放进度信息
     */
    updateAudioProgress(progress) {
        // 可以在这里添加音频进度条的更新逻辑
        console.log('音频播放进度:', progress);
        
        // 如果有音频进度条元素，可以在这里更新
        const progressBar = document.querySelector('.audio-progress');
        if (progressBar) {
            progressBar.style.width = `${progress.percentage}%`;
        }
        
        // 更新时间显示
        const timeDisplay = document.querySelector('.audio-time');
        if (timeDisplay) {
            const current = this.formatTime(progress.currentTime);
            const total = this.formatTime(progress.duration);
            timeDisplay.textContent = `${current} / ${total}`;
        }
    }
    
    /**
     * 格式化时间显示
     * @param {number} seconds - 秒数
     * @returns {string} 格式化的时间字符串
     */
    formatTime(seconds) {
        if (isNaN(seconds)) return '00:00';
        
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }
}